package com.yoomiito.app.utils;

import static com.yoomiito.app.utils.ImageUtils.getTempFileName;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.yoomiito.app.R;
import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutionException;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.schedulers.Schedulers;
import jp.wasabeef.glide.transformations.BlurTransformation;

/**
 * 第三方图片加载库的封装类，方便随时更换第三方
 */
public class ImageLoader {

    public static ImageLoader getInstance() {
        return ImageLoaderHolder.imageLoader;
    }

    private static class ImageLoaderHolder {
        public static ImageLoader imageLoader = new ImageLoader();
    }

    /**
     * @param context   Context
     * @param url       图片加载地址
     * @param imageView view
     */
    public void into(Context context, String url, ImageView imageView) {
        if (context != null) {
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.goods_default);
            Glide.with(context).load(url).apply(requestOptions).into(imageView);
        }
    }

    /**
     * @param context   Activity
     * @param url       图片加载地址
     * @param imageView view
     */
    public void into(Activity context, String url, ImageView imageView) {
        if (context != null) {
            Glide.with(context).load(url).into(imageView);
        }
    }

    /**
     * @param context   Fragment
     * @param url       图片加载地址
     * @param imageView view
     */
    public void into(Fragment context, String url, ImageView imageView) {
        if (context != null) {
            Glide.with(context).load(url).into(imageView);
        }
    }

    /**
     * @param context   Context
     * @param url       图片加载地址
     * @param imageView view
     * @param resId     占位图
     */
    public void into(Context context, String url, ImageView imageView, int resId) {
        if (context != null) {
            Glide.with(context).load(url).apply(requestOptions(resId)).into(imageView);
        }
    }

    /**
     * @param context   Fragment
     * @param url       图片加载地址
     * @param imageView view
     * @param resId     占位图
     */
    public void into(Fragment context, String url, ImageView imageView, int resId) {
        if (context != null) {
            Glide.with(context).load(url).apply(requestOptions(resId)).into(imageView);
        }
    }

    public void intoAllSize(Fragment context, String url, ImageView imageView, int resId){
        if (context != null) {
            Glide.with(context).load(url).apply(requestOptions(resId).override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)).into(imageView);
        }
    }

    public void intoAllSize(Context context, String url, ImageView imageView, int resId){
        if (context != null) {
            Glide.with(context).load(url).apply(requestOptions(resId).override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)).into(imageView);
        }
    }



    /**
     * @param context   Activity
     * @param url       图片加载地址
     * @param imageView view
     * @param resId     占位图
     */
    public void into(Activity context, String url, ImageView imageView, int resId) {
        if (context != null) {
            Glide.with(context).load(url).apply(requestOptions(resId)).into(imageView);
        }
    }

    /**
     * 圆角图片
     *
     * @param activity
     * @param url
     * @param radius
     * @param imageView
     */
    public void into(Context activity, String url, int radius, ImageView imageView, int resId) {
        RoundedCorners corners = new RoundedCorners(radius);
        RequestOptions options = RequestOptions.bitmapTransform(corners);
        options.error(resId);
        options.placeholder(resId);
        Glide.with(activity).load(url).apply(options).into(imageView);
    }

    public void into(Context activity, String url, int radius, ImageView imageView) {
        RoundedCorners corners = new RoundedCorners(radius);
        RequestOptions options = RequestOptions.bitmapTransform(corners);
        options.error(R.drawable.goods_default);
        options.placeholder(R.drawable.goods_default);
        Glide.with(activity).load(url).apply(options).into(imageView);
    }

    /**
     * 圆角图片
     *
     * @param activity
     * @param url
     * @param radius
     * @param imageView
     */
    public void into(Activity activity, Bitmap url, int radius, ImageView imageView) {
        RoundedCorners corners = new RoundedCorners(radius);
        RequestOptions options = RequestOptions.bitmapTransform(corners);
        Glide.with(activity).load(url).apply(options).into(imageView);
    }

    public void downloadPic(final Context context, String url) {
//        Observable.just(url)
//                .subscribeOn(Schedulers.io())
//                .map(s -> )
//                .subscribe(file -> ImageUtils.saveImage(context, ImageUtils.getBitmapByFile(file)));
        download(context, url);
    }

    public void downloadPic(final Context context, List<String> urls) {
        Observable.fromIterable(urls)
                .subscribeOn(Schedulers.io())
                .map(url -> download(context, url))
                .subscribe(file -> ImageUtils.saveImage(context, ImageUtils.getBitmapByFile(file)));
    }

    public void downloadPic(final Context context, final Bitmap bitmap) {
        if (bitmap==null)return;
        Observable.create((ObservableOnSubscribe<Bitmap>) emitter -> emitter.onNext(bitmap))
                .subscribeOn(Schedulers.io())
                .subscribe(bitmap1 -> ImageUtils.saveImage(context, bitmap1));
    }

    private File download(Context context, String url) {
        try {
            Glide.with(context).asBitmap().load(context).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                    ImageUtils.saveImage(context, resource);
                }
            });
            Glide.with(context)
                    .asFile()
                    .load(url)
                    .downloadOnly(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
                           FileUtils.INSTANCE.createSaveFile(
                                    context,
                                    resource,
                                    1,
                                    getTempFileName()+".jpg",
                                    "sharePic"
                            );


//                            String filePath = resource.getAbsolutePath();

//                            FileUtil.copy(resource, FileUtil.createFile(App.getApplication().getFilesDir()+"","/sharePic/"+getTempFileName()+".jpg"));
//                            ImageUtils.saveImage(context, ImageUtils.getBitmapByFile(resource));
                        }
                    });

            return Glide.with(context)
                    .downloadOnly()
                    .load(url)
                    .submit()
                    .get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }



//    private File download(Context context, String url) {
//        final File[] file = new File[1];
//        try {
//            Glide.with(context)
//                    .downloadOnly()
//                    .load(url)
//                    .addListener(new RequestListener<File>() {
//                        @Override
//                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
//                            return false;
//                        }
//
//                        @Override
//                        public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
//                            ImageUtils.saveImage(context, ImageUtils.getBitmapByFile(resource));
//                            return false;
//                        }
//                    }).preload();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return file[0];
//    }



    private RequestOptions requestOptions(int resId) {
        RequestOptions options = new RequestOptions();
        options.error(resId)
                .placeholder(resId)
                .priority(Priority.HIGH)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        return options;
    }



    /**
     *
     *
     * 高斯模糊
     *
     * @param context
     * @param url
     * @param imageView
     */
    public void loadGaussianBlur(final Context context,int radius, String url,ImageView imageView){
        Glide.with(context)
                .load(url)
                .apply(RequestOptions.bitmapTransform(new BlurTransformation(radius)))
                .into(imageView);
    }

    /**
     * 高斯模糊
     *
     * @param context
     *
     * @param resId
     * @param imageView
     */
    public void loadGaussianBlur(final Context context, int resId,ImageView imageView){
        Glide.with(context)
                .load(resId)
                .apply(RequestOptions.bitmapTransform(new BlurTransformation()))
                .into(imageView);
    }


    private static Activity mContext;
    private static final int REQUEST_CODE_SAVE_IMG = 0;



}
